package com.yonyou.wdt.utils;

import lombok.Data;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class RateLimiter {

    private final Semaphore semaphore;
    private final AtomicInteger callCount;
    private volatile long lastResetTime;
    private final int maxCallsPerMinute; // 每分钟允许的最大调用次数

    public RateLimiter(int maxCallsPerMinute) {
        this.maxCallsPerMinute = maxCallsPerMinute;
        this.semaphore = new Semaphore(maxCallsPerMinute);
        this.callCount = new AtomicInteger(0);
        this.lastResetTime = System.currentTimeMillis();
    }

    public boolean call() {
        long currentTime = System.currentTimeMillis();

        // 确保每分钟重置一次计数器，并严格控制重置频率
        synchronized (this) {
            if (currentTime - lastResetTime >= TimeUnit.MINUTES.toMillis(1)) {
                lastResetTime = currentTime;
                int currentAvailablePermits = semaphore.availablePermits();
                // 重置信号量，确保重新填充
                semaphore.release(maxCallsPerMinute - currentAvailablePermits);
                callCount.set(0);
            }
        }
        // 获取信号量，确保严格的限流控制
        try {
            if (semaphore.tryAcquire(1, TimeUnit.SECONDS)) {
                int currentCount = callCount.incrementAndGet();
                if (currentCount > maxCallsPerMinute) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } catch (InterruptedException e) {
            return true;
        }
    }

}